#include "FileDriver.h"
#include "stdio.h"
#include "sys/stat.h"

FileDriver::FileDriver()
:m_is_open(false)
{
}

bool FileDriver::file_open(string filename)
{
	m_filename.append(filename);

	if(true == m_is_open) {
		file_close();
	}

	m_fstream.open(filename.c_str(),
			ios::in | fstream::out |
			fstream::app | fstream::binary);
	if(true == m_fstream.fail()) {
		cout<<"FileDriver::file_open: Fail to open file: "
				<<filename<<endl;
		cout<<"The failure reason is: "<<m_fstream.rdstate()<<endl;
		return false;
	}

	m_is_open = true;
	return true;
}

void FileDriver::file_close() {
	m_fstream.clear();
	m_fstream.close();
	m_is_open = false;
}

uint64_t FileDriver::file_size()
{
	uint64_t file_length;

	m_fstream.seekg (0, ios::end);
	file_length = m_fstream.tellg();
	m_fstream.seekg (0, ios::beg);

//	FILE* p_file = fopen(m_filename.c_str(), "r");
	/*struct stat stat_info;
	if(-1 == stat(m_filename.c_str(), &stat_info)) {
		cout<<"Fail to stat file "<<m_filename<<" with reason "<<errno<<endl;
		return -1;
	}
	cout<<"The size of file "<<m_filename<<" is: "<<stat_info.st_size<<endl;*/

	cout<<"The size of file "<<m_filename<<" is: "<<file_length<<endl;
	return file_length;
//	return stat_info.st_size;
}

int FileDriver::file_write(void* buffer, size_t write_size) {
	if(true == m_is_open && NULL != buffer) {
		m_fstream .write((char*)buffer, write_size);
		if(true == m_fstream.good()) {
			return 0;
		}
		else {
			cout<<"FileDriver::file_write: "
					"Error occurred when write"
					" buffer content to file"
					<<endl;
			return -1;
		}
	}
	else if(false == m_is_open) {
		cout<<"FileDriver::file_write: "
				"Error occurred, FileDriver has not "
				"opened any file."<<endl;
		return -2;
	}
	else {
		cout<<"FileDriver::file_write: "
				"Buffer to be wrote is empty"<<endl;
		return -3;
	}
}

int FileDriver::file_read(void* buffer, size_t read_size) {
	if(true == m_is_open && NULL != buffer) {
		m_fstream.read((char*)buffer, read_size);
//		cout<<"Buffer read from file is: "<<endl<<(char*)buffer<<endl;
		return m_fstream.gcount();
	/*	if(true != m_fstream.fail()) {
			return 0;
		}
		else {
			cout<<"FileDriver::file_read: "
					"Error occurred when read"
					" content into buffer "
					"from file"<<endl;
			return -1;
		}*/
	}
	else if(false == m_is_open) {
		cout<<"FileDriver::file_read: "
				"Error occurred, FileDriver has not "
				"opened any file."<<endl;
		return -2;
	}
	else {
		cout<<"FileDriver::file_read: "
				"The buffer to be read is empty"<<endl;
		return -3;
	}
}
